package leetcode;

import java.util.PriorityQueue;
import java.util.TreeSet;

public class LC1705 {

    public static int eatenApples(int[] apples, int[] days) {
        int cnt = 0;

        //优先队列保存i天之前的苹果腐烂的截止时间，从小到大，即之前没有吃完的
        PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((a,b) -> a[0] - b[0]);

        for (int i = 0; i < apples.length; i++) {
            if (apples[i] > 0 && days[i] > 0) {
                priorityQueue.offer(new int[]{days[i] + i,apples[i]});
            }
            if (priorityQueue.isEmpty()) {
            } else {
                while (!priorityQueue.isEmpty()) {
                    int[] tmp = priorityQueue.peek();
                    if (tmp[0] > i) { //最近要过期的苹果至今还没过期，就吃它
                        priorityQueue.poll();
                        tmp[1] --;
                        cnt ++;
                        if (tmp[1] > 0) {
                            priorityQueue.offer(tmp);
                        }
                        break;
                    } else {
                        priorityQueue.poll(); // 最近过期的苹果到今天已经过去，丢掉
                    }
                }
            }
        }
        if (!priorityQueue.isEmpty()) {
            for (int i = apples.length; !priorityQueue.isEmpty() ; i++) {
                while (!priorityQueue.isEmpty()) {
                    int[] tmp = priorityQueue.peek();
                    if (tmp[0] > i) {
                        tmp[1]--;
                        cnt++;
                        priorityQueue.poll();
                        if (tmp[1] > 0) {
                            priorityQueue.offer(tmp);
                        }
                        break;
                    } else priorityQueue.poll();
                }
            }
        }
        return cnt;
    }

    public static void main(String[] args) {
        System.out.println(eatenApples(new int[]{2,1,10}, new int[]{2,10,1}));
    }

}
